<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <el-button
        v-if="cartGroupBySeller.length > 0 && hasLogin"
        type="danger"
        @click="batchDelete"
        :disabled="!hasSelectedItems"
      >
        批量删除
      </el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="!hasLogin" class="empty-cart">
      <el-empty description="请先登录" />
      <el-button type="primary" @click="goLogin">去登录</el-button>
    </div>

    <div v-else-if="cartGroupBySeller.length === 0" class="empty-cart">
      <el-empty description="购物车空空如也" />
      <el-button type="primary" @click="goHome">去购物</el-button>
    </div>

    <div v-else class="cart-content-wrapper">
      <div class="cart-content">
        <!-- 商家分组购物车 -->
        <div v-for="sellerGroup in cartGroupBySeller" :key="sellerGroup.sellerId" class="seller-group">
          <div class="seller-header">
            <el-checkbox v-model="sellerGroup.checked" @change="handleSellerCheck(sellerGroup)">
              <span class="seller-name">
                商家:
                <span class="seller-link" @click.stop="goToSellerPage(sellerGroup.sellerId)">
                  {{ sellerGroup.sellerName || `商家${sellerGroup.sellerId}` }} &gt;
                </span>
              </span>
            </el-checkbox>
          </div>

          <div class="cart-items">
            <div v-for="item in sellerGroup.items" :key="item.id" class="cart-item">
              <div class="item-checkbox">
                <el-checkbox v-model="item.checked" @change="handleItemCheck">
                </el-checkbox>
              </div>

              <div class="item-image" @click="goToProductDetail(item.productId)" style="cursor: pointer;">
                <el-image :src="item.productImage" fit="cover" />
              </div>

              <div class="item-info">
                <div class="item-name">{{ item.productName }}</div>
                <div class="item-sku">{{ item.skuName }}</div>
                <div class="item-price">¥{{ item.price }}</div>
              </div>

              <div class="item-quantity">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="9999"
                  size="small"
                  @change="handleQuantityChange(item)"
                />
              </div>

              <div class="item-actions">
                <el-button
                  type="text"
                  size="small"
                  @click="showSkuDialog(item)"
                >
                  修改规格
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  danger
                  @click="deleteItem(item.id)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="cart-footer">
      <div class="select-all">
        <el-checkbox v-model="isAllSelected" @change="handleSelectAll">全选</el-checkbox>
      </div>

      <div class="total-info">
        <span>合计: </span>
        <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>

      <div class="action-buttons">
        <el-button 
          type="primary" 
          size="large"
          @click="handleCheckout"
          :disabled="!hasSelectedItems || orderLoading"
        >
          <span v-if="orderLoading">下单中...</span>
          <span v-else>结算</span>
        </el-button>
      </div>
    </div>

    <!-- 修改规格对话框 -->
    <el-dialog
      v-model="skuDialogVisible"
      title="修改商品规格"
      width="500px"
    >
      <div v-if="loadingSkus" class="loading-skus">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-else-if="skus.length === 0">
        <el-empty description="暂无规格信息" />
      </div>
      <div v-else>
        <div class="product-info">
          <h3>{{ currentSkuDialogProduct.productName }}</h3>
        </div>

        <div class="sku-options">
          <el-radio-group v-model="selectedSkuId">
            <el-radio
              v-for="sku in skus"
              :key="sku.id"
              :label="sku.id"
              :disabled="sku.stock === 0 || sku.status === 0"
              :class="{ 'disabled': sku.stock === 0 || sku.status === 0 }"
            >
              <div class="sku-option">
                <span>{{ sku.name }}</span>
                <span class="sku-price">¥{{ sku.price }}</span>
              </div>
            </el-radio>
          </el-radio-group>
        </div>

        <div class="quantity-control">
          <label>数量: </label>
          <el-input-number
            v-model="currentSkuDialogProduct.quantity"
            :min="1"
            :max="9999"
            size="small"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="skuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSkuUpdate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 地址确认弹窗 -->
    <div v-if="showAddressConfirm" class="address-confirm-modal" @click="closeAddressConfirm">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认收货地址</h3>
          <button class="close-btn" @click="closeAddressConfirm">×</button>
        </div>
        <div class="modal-body">
          <div class="address-section">
            <div class="address-label">
              <span class="icon">📍</span>
              <span>收货地址</span>
            </div>
            <div class="address-input-container">
              <textarea
                v-model="editableAddress"
                class="address-input"
                placeholder="请输入详细的收货地址"
                rows="3"
                :disabled="addressLoading"
              ></textarea>
            </div>
            <div class="address-tips">
              <span class="tip-icon">💡</span>
              <span>请确认地址信息准确无误，以免影响商品配送</span>
            </div>
          </div>
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">商品数量：</span>
              <span class="value">{{ selectedItemsQuantity }}件</span>
            </div>
            <div class="summary-item total">
              <span class="label">总金额：</span>
              <span class="value price">￥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddressConfirm" :disabled="orderLoading">
            取消
          </button>
          <button class="confirm-btn" @click="confirmAddressAndOrder" :disabled="orderLoading || !editableAddress.trim()">
            <span v-if="orderLoading" class="loading-spinner"></span>
            {{ orderLoading ? '下单中...' : '确认下单' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 订单成功弹窗 -->
    <div v-if="orderSuccess" class="order-success-modal" @click="closeOrderSuccess">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>下单成功！</h3>
          <button class="close-btn" @click="closeOrderSuccess">×</button>
        </div>
        <div class="modal-body">
          <div class="success-icon">✓</div>
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ orderResult?.orderId }}</span>
            </div>
            <div class="info-item">
              <span class="label">收货人：</span>
              <span class="value">{{ orderResult?.customerName || '用户' }}</span>
            </div>
            <div class="info-item">
              <span class="label">商品数量：</span>
              <span class="value">{{ selectedItemsQuantity }}件</span>
            </div>
            <div class="info-item">
              <span class="label">订单金额：</span>
              <span class="value price">￥{{ orderResult?.totalPrice }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span class="value">{{ orderResult?.createTime }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="continue-btn" @click="closeOrderSuccess">继续购物</button>
          <button class="view-order-btn" @click="viewOrderDetail">查看订单</button>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="showError" class="error-toast">
      <div class="error-content">
        <span class="error-icon">⚠</span>
        <span class="error-text">{{ errorMessage }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCartListByCustomerId, deleteCartItems, updateCartItem } from '../api/user'
import axios from 'axios'
import { getSellerInfoById } from '../api/seller'

export default {
  name: 'CartView',
  setup() {
    const router = useRouter()

    // 响应式数据
    const cartList = ref([])
    const loading = ref(false)
    const loadingSkus = ref(false)
    const skus = ref([])
    const skuDialogVisible = ref(false)
    const selectedSkuId = ref(null)
    const currentSkuDialogProduct = ref({})
    const cartGroupBySeller = ref([])

    // 响应式数据
    const hasLogin = ref(false)

    // 地址确认和订单相关状态
    const showAddressConfirm = ref(false)
    const customerAddress = ref('')
    const editableAddress = ref('')
    const addressLoading = ref(false)
    const orderLoading = ref(false)
    const orderSuccess = ref(false)
    const orderResult = ref(null)
    
    // 错误处理状态
    const errorMessage = ref('')
    const showError = ref(false)

    // 检查登录状态
    const checkLoginStatus = () => {
      const token = localStorage.getItem('userToken')
      const userRoles = localStorage.getItem('userRoles')

      // 检查token和roles是否都存在，并验证是否有CUSTOMER角色
      if (token && userRoles) {
        try {
          const roles = JSON.parse(userRoles)
          const hasCustomerRole = roles.some(role => role.code === 'CUSTOMER')
          if (hasCustomerRole) {
            hasLogin.value = true
          } else {
            hasLogin.value = false
          }
        } catch (error) {
          console.error('解析userRoles失败:', error)
          hasLogin.value = false
        }
      } else {
        hasLogin.value = false
      }
    }

    const isAllSelected = computed({
      get: () => {
        if (cartGroupBySeller.value.length === 0) return false
        return cartGroupBySeller.value.every(seller => seller.checked)
      },
      set: (value) => {
        cartGroupBySeller.value.forEach(seller => {
          seller.checked = value
          seller.items.forEach(item => {
            item.checked = value
          })
        })
      }
    })

    const selectedItems = computed(() => {
      const items = []
      cartGroupBySeller.value.forEach(seller => {
        items.push(...seller.items.filter(item => item.checked))
      })
      return items
    })

    const hasSelectedItems = computed(() => {
      return selectedItems.value.length > 0
    })

    const totalPrice = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    })

    const selectedItemsQuantity = computed(() => {
      return selectedItems.value.reduce((total, item) => {
        return total + (item.quantity || 0)
      }, 0)
    })

    // 获取顾客ID
    const getCustomerId = () => {
      // 从userRoles数组中获取customerId
      const userRolesStr = localStorage.getItem('userRoles')
      if (userRolesStr) {
        try {
          const userRoles = JSON.parse(userRolesStr)
          const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
          return customerRole ? Number(customerRole.id) : null
        } catch (error) {
          console.error('解析userRoles失败:', error)
          return null
        }
      }
      return null
    }

    // 方法
    const loadCartData = async () => {
      if (!hasLogin.value) return

      loading.value = true
      try {
        // 使用与CustomerOrderManage相同的方式获取顾客ID
        const customerId = getCustomerId()

        // 验证customerId的有效性
        if (!customerId || isNaN(customerId) || customerId <= 0) {
          console.warn('未找到有效customerId:', customerId)
          ElMessage.warning('未找到有效顾客信息，请重新登录')
          cartList.value = []
          cartGroupBySeller.value = []
          loading.value = false
          return
        }

        // 根据http.js响应拦截器，getCartListByCustomerId已直接返回response.data
        const response = await getCartListByCustomerId(customerId)
        // 直接从响应中获取list，不再需要访问response.data
        cartList.value = (response && response.list) || []

        // 获取每个商品的SKU信息，以获取准确的库存数据
        const productsWithSkus = await Promise.all(
          cartList.value.map(async (item) => {
            try {
              // 获取商品的SKU列表，使用axios直接调用API
              const response = await axios.get(`/api/product/queryByPId/${item.productId}`)
              // 获取response中的data
              const skus = response?.data || []
              // 查找当前SKU的库存信息
              const currentSku = skus.find(sku => sku.id === item.skuId)
              // 如果找到当前SKU，则添加库存信息
              if (currentSku && currentSku.stock !== undefined && currentSku.status !== undefined) {
                return {
                  ...item,
                  stock: currentSku.stock, // 添加库存信息
                  status: currentSku.status // 添加状态信息
                }
              }
            } catch (error) {
              console.error(`获取商品${item.productId}的SKU信息失败:`, error)
              // 错误时继续，不阻止加载流程
            }
            return item
          })
        )

        // 更新cartList为包含库存信息的数据
        cartList.value = productsWithSkus

        // 构建商家分组
        const groups = {}
        cartList.value.forEach(item => {
          if (!groups[item.sellerId]) {
            groups[item.sellerId] = {
              sellerId: item.sellerId,
              sellerName: `商家${item.sellerId}`,
              checked: false,
              items: []
            }
          }
          groups[item.sellerId].items.push({
            ...item,
            checked: false
          })
        })

        // 获取商家详细信息
        const sellerPromises = Object.keys(groups).map(async (sellerId) => {
          // 添加对null或空字符串商家ID的检查
          if (!sellerId || sellerId === 'null') {
            console.warn('无效的商家ID:', sellerId)
            return
          }

          try {
            const sellerInfo = await getSellerInfoById(sellerId)
            // 同时检查name和shopName字段，确保能正确显示详细商铺名称
            if (sellerInfo) {
              groups[sellerId].sellerName = sellerInfo.shopName || sellerInfo.name || `商家${sellerId}`
            }
          } catch (error) {
            console.error(`获取商家${sellerId}信息失败:`, error)
          }
        })

        // 等待所有商家信息加载完成
        await Promise.all(sellerPromises)

        // 更新cartGroupBySeller
        cartGroupBySeller.value = Object.values(groups)
      } catch (error) {
        console.error('加载购物车数据失败:', error)
        ElMessage.error('加载购物车数据失败')
        // 确保cartList和cartGroupBySeller为空数组
        cartList.value = []
        cartGroupBySeller.value = []
      } finally {
        loading.value = false
      }
    }

    const handleSellerCheck = (sellerGroup) => {
      sellerGroup.items.forEach(item => {
        item.checked = sellerGroup.checked
      })
    }

    const handleItemCheck = () => {
      // 更新商家的选中状态
      cartGroupBySeller.value.forEach(seller => {
        seller.checked = seller.items.every(item => item.checked)
      })
    }

    const handleSelectAll = () => {
      // isAllSelected的setter会处理所有选中状态
    }

    const handleQuantityChange = async (item) => {
      // 前端基本验证 - 只检查最小值，不检查最大值上限
      if (item.quantity <= 0) {
        ElMessage.warning('商品数量不能小于等于0')
        item.quantity = 1 // 重置为1
        return
      }

      let overStock = false
      let availableStock = 0
      let existingQuantity = 0

      try {
        // 获取最新的购物车数据，以准确计算相同SKU的数量
        const customerId = getCustomerId()
        if (!customerId) {
          ElMessage.warning('无法获取顾客信息，请重新登录')
          return
        }

        // 调用API获取最新的购物车列表
        const cartResponse = await getCartListByCustomerId(Number(customerId))
        const cartItems = cartResponse && cartResponse.list ? cartResponse.list : []

        // 计算购物车中已有的相同SKU数量（不包括当前正在修改的商品）
        existingQuantity = 0
        for (const cartItem of cartItems) {
          if (cartItem.skuId === item.skuId && cartItem.id !== item.id) {
            // 其他相同SKU的商品，累加数量
            existingQuantity += cartItem.quantity
          }
        }

        // 检查是否超过库存
        if (item.stock) {
          // 可用库存 = 总库存 - 购物车中已有的数量（不包括当前正在修改的商品数量）
          availableStock = Math.max(0, item.stock - existingQuantity)
          overStock = item.quantity > availableStock
        }
      } catch (error) {
        console.error('获取购物车数据失败:', error)
        ElMessage.error('获取购物车数据失败，请重试')
        return
      }

      // 提交前检查是否超过库存
      if (overStock) {
        if (availableStock > 0) {
          ElMessage.warning(`超过库存数量`)
          // 调整为可用库存数量
          item.quantity = availableStock
          return
        } else {
          ElMessage.warning(`库存不足，考虑您购物车中已有的${existingQuantity}件，该商品暂无可用库存`)
          item.quantity = 0
          return
        }
      }

      try {
        await updateCartItem({
          id: item.id,
          skuId: item.skuId,
          quantity: item.quantity
        })
        ElMessage.success('数量更新成功')
      } catch (error) {
        console.error('更新数量失败:', error)
        // 更全面地检查错误信息
        let errorMessage = '更新数量失败'
        if (error.response?.data?.message) {
          // 检查是否是库存不足的错误
          if (error.response.data.message.includes('库存') || error.response.data.message.includes('stock')) {
            errorMessage = error.response.data.message
          } else {
            errorMessage = error.response.data.message
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
      }
    }

    const showSkuDialog = async (product) => {
      currentSkuDialogProduct.value = { ...product }
      selectedSkuId.value = product.skuId
      loadingSkus.value = true

      try {
        // 直接获取当前商品的SKU列表，而不是重新加载整个购物车数据
        const response = await axios.get(`/api/product/queryByPId/${product.productId}`)
        skus.value = response?.data || []

        // 查找当前SKU的库存信息并更新到currentSkuDialogProduct
        const currentSku = skus.value.find(sku => sku.id === product.skuId)
        if (currentSku && currentSku.stock !== undefined && currentSku.status !== undefined) {
          currentSkuDialogProduct.value.stock = currentSku.stock
          currentSkuDialogProduct.value.status = currentSku.status
        }

        // 使用watch监听selectedSkuId变化，更新库存信息
        const unwatch = watch(selectedSkuId, (newSkuId) => {
          const selectedSku = skus.value.find(sku => sku.id === newSkuId)
          if (selectedSku && selectedSku.stock !== undefined && selectedSku.status !== undefined) {
            currentSkuDialogProduct.value.stock = selectedSku.stock
            currentSkuDialogProduct.value.status = selectedSku.status

            // 基于当前顾客购物车的库存检查逻辑
            // 找出当前顾客购物车中所有相同商品SKU的条目
            const sameSkuItems = cartList.value.filter(
              cartItem => cartItem.skuId === newSkuId && cartItem.id !== currentSkuDialogProduct.value.id
            )

            // 计算当前商品在购物车中的其他数量总和
            const otherQuantitySum = sameSkuItems.reduce((sum, cartItem) => sum + cartItem.quantity, 0)

            // 计算可用库存
            const availableStock = Math.max(0, selectedSku.stock - otherQuantitySum)

            // 显示库存信息，但不自动调整数量，让用户可以继续输入
            if (currentSkuDialogProduct.value.quantity > availableStock) {
              if (availableStock > 0) {
                ElMessage.warning(`当前数量超过可用库存`)
              } else {
                ElMessage.warning(`当前数量超过可用库存，考虑您购物车中已有的件数，该商品暂无可用库存`)
              }
            }
          }
        })

        // 在对话框关闭时取消监听
        watch(skuDialogVisible, (newVal) => {
          if (!newVal) {
            unwatch()
          }
        })

        // 检查当前选中的SKU是否可用
        const currentSelectedSku = skus.value.find(sku => sku.id === selectedSkuId.value)
        if (!currentSelectedSku || currentSelectedSku.stock === 0 || currentSelectedSku.status === 0) {
          // 如果当前选中的SKU不可用，则尝试查找第一个可用的SKU
          const firstAvailableSku = skus.value.find(sku => sku.stock > 0 && sku.status === 1)
          if (firstAvailableSku) {
            selectedSkuId.value = firstAvailableSku.id
          } else {
            // 如果没有可用的SKU，则不选择任何SKU
            selectedSkuId.value = null
          }
        }
      } catch (error) {
        console.error('获取SKU信息失败:', error)
        ElMessage.error('获取规格信息失败')
        skus.value = []
      } finally {
        loadingSkus.value = false
      }

      skuDialogVisible.value = true
    }

    const confirmSkuUpdate = async () => {
      if (!selectedSkuId.value) {
        ElMessage.warning('请选择规格')
        return
      }

      // 前端基本验证
      if (currentSkuDialogProduct.value.quantity <= 0) {
        ElMessage.warning('商品数量不能小于等于0')
        currentSkuDialogProduct.value.quantity = 1 // 重置为1
        return
      }

      // 基于当前顾客购物车的库存检查逻辑
      // 找出当前顾客购物车中所有相同商品SKU的条目
      const sameSkuItems = cartList.value.filter(
        cartItem => cartItem.skuId === selectedSkuId.value && cartItem.id !== currentSkuDialogProduct.value.id
      )

      // 计算当前商品在购物车中的其他数量总和
      const otherQuantitySum = sameSkuItems.reduce((sum, cartItem) => sum + cartItem.quantity, 0)

      // 检查是否超过库存
      if (currentSkuDialogProduct.value.stock) {
        const availableStock = Math.max(0, currentSkuDialogProduct.value.stock - otherQuantitySum)
        if (currentSkuDialogProduct.value.quantity > availableStock && availableStock > 0) {
          ElMessage.warning(`超过库存数量`)
          currentSkuDialogProduct.value.quantity = availableStock
          return
        } else if (currentSkuDialogProduct.value.quantity > availableStock && availableStock === 0) {
          ElMessage.warning(`库存不足，考虑您购物车中已有的${otherQuantitySum}件，该商品暂无可用库存`)
          currentSkuDialogProduct.value.quantity = 0
          return
        }
      }

      try {
        // 检查是否存在相同规格的商品
        const existingItem = cartList.value.find(
          item => item.productId === currentSkuDialogProduct.value.productId &&
            item.skuId === selectedSkuId.value &&
            item.id !== currentSkuDialogProduct.value.id
        )

        if (existingItem) {
          // 存在相同规格，合并数量 (将原商品数量与新商品数量相加)
          let totalQuantity = existingItem.quantity + currentSkuDialogProduct.value.quantity

          // 计算可用库存：总库存 - (其他相同SKU的商品数量总和 - 当前正在合并的existingItem数量)
          const adjustedOtherQuantity = otherQuantitySum - existingItem.quantity
          const availableStock = Math.max(0, currentSkuDialogProduct.value.stock - adjustedOtherQuantity)

          // 直接调整数量到最大可用库存，不进行提示
          totalQuantity = Math.min(totalQuantity, availableStock)

          await updateCartItem({
            id: existingItem.id,
            skuId: existingItem.skuId,
            quantity: totalQuantity
          })
          // 删除原商品
          await deleteCartItems([currentSkuDialogProduct.value.id])
          ElMessage.success('已将数量合并到现有规格，并删除原商品')
          skuDialogVisible.value = false // 确保对话框关闭
          await loadCartData() // 更新后重新加载购物车数据，确保界面正确显示
        } else {
          // 不存在相同规格，直接更新规格
          let quantity = currentSkuDialogProduct.value.quantity

          // 使用已计算的基于顾客购物车的可用库存
          const availableStock = Math.max(0, currentSkuDialogProduct.value.stock - otherQuantitySum)
          if (availableStock > 0 && quantity > availableStock) {
            ElMessage.warning(`数量超过库存限制，已调整为最大可用库存数量: ${availableStock}件`)
            quantity = availableStock
          }

          await updateCartItem({
            id: currentSkuDialogProduct.value.id,
            skuId: selectedSkuId.value,
            quantity: quantity
          })
          ElMessage.success('规格更新成功')
          skuDialogVisible.value = false // 确保对话框关闭
          await loadCartData() // 更新后重新加载购物车数据
        }
      } catch (error) {
        console.error('更新规格失败:', error)
        let errorMessage = '更新规格失败'
        if (error.response?.data?.message) {
          // 检查是否是库存不足的错误
          if (error.response.data.message.includes('库存') || error.response.data.message.includes('stock')) {
            errorMessage = error.response.data.message
          } else {
            errorMessage = error.response.data.message
          }
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
      }
    }

    const deleteItem = async (itemId) => {
      try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await deleteCartItems([itemId])
        ElMessage.success('删除成功')
        await loadCartData()
      } catch (error) {
        // 静默处理取消操作，不显示任何提示或日志
        if (error && error !== 'cancel' && error.message !== 'cancel' && error.name !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    const batchDelete = async () => {
      if (!hasSelectedItems.value) return

      try {
        await ElMessageBox.confirm('确定要删除选中的商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const ids = selectedItems.value.map(item => item.id)
        await deleteCartItems(ids)
        ElMessage.success('删除成功')
        await loadCartData()
      } catch (error) {
        // 静默处理取消操作，不显示任何提示或日志
        if (error && error !== 'cancel' && error.message !== 'cancel' && error.name !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    const goLogin = () => {
      router.push('/customer-login')
    }

    const goHome = () => {
      router.push('/')
    }

    // 跳转到商家页面，与商品详情页保持一致的路由路径
    const goToSellerPage = (sellerId) => {
      router.push(`/seller/${sellerId}`)
    }

    // 跳转到商品详情页
    const goToProductDetail = (productId) => {
      router.push(`/product/${productId}`)
    }

    // 显示错误提示
    const showErrorMessage = (message) => {
      errorMessage.value = message
      showError.value = true
      setTimeout(() => {
        showError.value = false
      }, 3000)
    }

    // 获取顾客地址
    const fetchCustomerAddress = async (customerId) => {
      try {
        addressLoading.value = true

        // 从localStorage获取token
        const token = localStorage.getItem('userToken')

        if (!token) {
          console.log('警告 - 获取地址时没有token，但继续尝试')
        }

        const headers = {
          'Content-Type': 'application/json'
        }

        // 只有当token存在时才添加Authorization头
        if (token) {
          headers['Authorization'] = `Bearer ${token}`
        }

        const response = await fetch(`/api/customer/queryCustomerAddress?customerId=${customerId}`, {
          method: 'GET',
          headers: headers
        })

        if (response.ok) {
          const address = await response.text()
          customerAddress.value = address
          editableAddress.value = address
          return address
        } else {
          // 如果是404或者地址不存在，不显示错误提示
          if (response.status === 404) {
            console.log('用户暂无设置地址')
            return null
          }
          throw new Error('获取地址失败')
        }
      } catch (error) {
        console.error('获取顾客地址失败:', error)
        // 不显示错误提示，让用户在弹窗中手动输入地址
        return null
      } finally {
        addressLoading.value = false
      }
    }

    // 关闭地址确认弹窗
    const closeAddressConfirm = () => {
      showAddressConfirm.value = false
      editableAddress.value = customerAddress.value
    }

    // 确认地址并创建订单
    const confirmAddressAndOrder = async () => {
      if (!editableAddress.value.trim()) {
        showErrorMessage('请输入收货地址')
        return
      }

      // 从localStorage获取用户信息
      const userToken = localStorage.getItem('userToken')
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]')
      
      if (!userToken || userRoles.length === 0) {
        showErrorMessage('用户未登录，请重新登录')
        return
      }

      // 从角色数组中获取CUSTOMER角色的ID
      const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
      const customerId = customerRole ? customerRole.id : null
      
      if (!customerId) {
        showErrorMessage('无法获取用户信息，请重新登录')
        return
      }

      // 构建订单数据
      const orderItemDTOS = selectedItems.value.map(item => ({
        sellerId: item.sellerId,
        skuId: item.skuId,
        productId: item.productId,
        address: editableAddress.value.trim(),
        productName: item.productName,
        quantity: item.quantity,
        price: item.price
      }))

      const orderData = {
        customerId: customerId,
        totalPrice: totalPrice.value,
        orderItemDTOS: orderItemDTOS
      }

      orderLoading.value = true
      showAddressConfirm.value = false

      try {
        // 获取token用于请求认证
        const token = localStorage.getItem('userToken')
        if (!token) {
          showErrorMessage('用户未登录，请重新登录')
          return
        }

        const response = await fetch('/api/orders/addOrder', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(orderData)
        })

        if (response.ok) {
          const result = await response.json()
          orderResult.value = result

          // 订单创建成功后，清空购物车中已选中的商品
          const selectedItemIds = selectedItems.value.map(item => item.id)
          await deleteCartItems(selectedItemIds)
          
          // 重新加载购物车数据
          await loadCartData()

          // 订单创建成功后直接跳转到订单详情页面
          if (result?.orderId) {
            router.push(`/order/${result.orderId}`)
          } else {
            // 如果没有订单ID，显示成功弹窗
            orderSuccess.value = true
          }
        } else {
          const errorData = await response.json()
          showErrorMessage(errorData.message || '下单失败，请稍后重试')
        }
      } catch (error) {
        console.error('下单失败:', error)
        showErrorMessage('网络错误，请检查网络连接后重试')
      } finally {
        orderLoading.value = false
      }
    }

    // 处理结算按钮点击
    const handleCheckout = async () => {
      // 清除之前的错误信息
      showError.value = false

      if (!hasSelectedItems.value) {
        showErrorMessage('请选择要结算的商品')
        return
      }

      // 检查用户登录状态
      const userToken = localStorage.getItem('userToken')
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]')

      if (!userToken || userRoles.length === 0) {
        showErrorMessage('请先登录后再结算')
        router.push('/customer-login')
        return
      }

      // 从角色数组中获取CUSTOMER角色的ID
      const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
      const customerId = customerRole ? customerRole.id : null

      if (!customerId) {
        showErrorMessage('无法获取顾客ID，请确认您有购买权限或重新登录')
        return
      }

      // 先显示弹窗，然后异步获取地址
      showAddressConfirm.value = true
      
      // 获取用户地址
      try {
        const address = await fetchCustomerAddress(customerId)
        if (!address) {
          // 如果获取地址失败，设置默认提示文本
          customerAddress.value = ''
          editableAddress.value = ''
        }
      } catch (error) {
        console.error('获取地址时出错:', error)
        // 即使获取地址失败，也保持弹窗显示，让用户手动输入
        customerAddress.value = ''
        editableAddress.value = ''
      }
    }

    // 关闭订单成功弹窗
    const closeOrderSuccess = () => {
      orderSuccess.value = false
      orderResult.value = null
    }

    // 查看订单详情
    const viewOrderDetail = () => {
      if (orderResult.value?.orderId) {
        router.push(`/order/${orderResult.value.orderId}`)
      }
      closeOrderSuccess()
    }

    // 生命周期
    onMounted(() => {
      checkLoginStatus()
      loadCartData()
    })

    return {
      loading,
      loadingSkus,
      cartGroupBySeller,
      skus,
      skuDialogVisible,
      selectedSkuId,
      currentSkuDialogProduct,
      hasLogin,
      isAllSelected,
      hasSelectedItems,
      totalPrice,
      selectedItemsQuantity,
      handleSellerCheck,
      handleItemCheck,
      handleSelectAll,
      handleQuantityChange,
      showSkuDialog,
      confirmSkuUpdate,
      deleteItem,
      batchDelete,
      goLogin,
      goHome,
      goToSellerPage,
      goToProductDetail,
      // 地址确认和订单相关
      showAddressConfirm,
      customerAddress,
      editableAddress,
      addressLoading,
      orderLoading,
      orderSuccess,
      orderResult,
      errorMessage,
      showError,
      showErrorMessage,
      fetchCustomerAddress,
      closeAddressConfirm,
      confirmAddressAndOrder,
      handleCheckout,
      closeOrderSuccess,
      viewOrderDetail
    }
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.cart-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  font-size: 24px;
  font-weight: 500;
}

.seller-link {
  color: #409eff;
  cursor: pointer;
  margin-left: 5px;
}

.seller-link:hover {
  text-decoration: underline;
}

.loading-container,
.empty-cart {
  padding: 40px 0;
  text-align: center;
}

.seller-group {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.seller-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.seller-name {
  font-weight: 500;
  margin-left: 5px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox {
  margin-right: 15px;
}

.item-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  overflow: hidden;
  border-radius: 4px;
}

.item-image img,
.item-image .el-image__inner {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 确保Element Plus的el-image组件正确应用尺寸 */
.item-image .el-image {
  width: 100%;
  height: 100%;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  min-height: 110px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  margin-bottom: 8px;
}

.item-sku {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.item-price {
  color: #f56c6c;
  font-weight: 500;
}

.item-quantity {
  margin: 0 30px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cart-content-wrapper {
  position: relative;
  margin-bottom: 20px;
}

.cart-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-height: calc(100vh - 300px);
  overflow-y: auto;
  padding-bottom: 30px;
}

.cart-content::-webkit-scrollbar {
  width: 8px;
}

.cart-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.cart-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.cart-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.cart-footer {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.action-buttons {
  flex-shrink: 0;
}

.select-all {
  flex-shrink: 0;
}

.total-info {
  flex: 1;
  text-align: right;
  margin-right: 30px;
}

.total-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: 500;
}

.sku-option {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.sku-price {
  color: #f56c6c;
  font-weight: 500;
}

.quantity-control {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.sku-option .stock-status {
  color: #f56c6c;
  font-size: 0.8em;
  margin-left: 5px;
}

.el-radio.disabled {
  .el-radio__input.is-disabled + span.el-radio__label {
    color: #a0a0a0 !important;
    cursor: not-allowed;
  }
  .sku-option {
    color: #a0a0a0 !important;
    cursor: not-allowed;
  }
  .sku-price {
    color: #a0a0a0 !important;
  }
}

.el-radio.is-disabled .el-radio__input.is-disabled + span.el-radio__label {
  color: #a0a0a0 !important;
  cursor: not-allowed;
}

.el-radio.is-disabled .sku-option {
  color: #a0a0a0 !important;
  cursor: not-allowed;
}

.el-radio.is-disabled .sku-price {
  color: #a0a0a0 !important;
}

/* 地址确认弹窗样式 */
.address-confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.address-confirm-modal .modal-content {
  background: white;
  border-radius: 12px;
  padding: 0;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 20px 24px;
}

.address-section {
  margin-bottom: 24px;
}

.address-label {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 500;
  color: #333;
}

.address-label .icon {
  margin-right: 8px;
  font-size: 16px;
}

.address-input-container {
  position: relative;
}

.address-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e1e1;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
  box-sizing: border-box;
  resize: vertical;
  min-height: 80px;
}

.address-input:focus {
  outline: none;
  border-color: #409eff;
}

.address-input::placeholder {
  color: #999;
}

.address-tips {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border-radius: 6px;
  font-size: 12px;
  color: #666;
}

.address-tips .tip-icon {
  margin-right: 6px;
  font-size: 14px;
}

.order-summary {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.summary-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  font-size: 16px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item.total {
  border-top: 1px solid #e1e1e1;
  padding-top: 8px;
  margin-top: 8px;
  font-weight: 600;
}

.summary-item .label {
  color: #666;
}

.summary-item .value {
  color: #333;
  font-weight: 500;
}

.summary-item .value.price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
}

.modal-footer {
  padding: 16px 24px 24px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  min-width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.cancel-btn:hover:not(:disabled) {
  background-color: #e8e8e8;
}

.confirm-btn {
  background-color: #409eff;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #337ecc;
}

.cancel-btn:disabled, .confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading-spinner {
  width: 14px;
  height: 14px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 订单成功弹窗样式 */
.order-success-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.order-success-modal .modal-content {
  background: white;
  border-radius: 12px;
  padding: 0;
  width: 90%;
  max-width: 450px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.success-icon {
  text-align: center;
  padding: 30px 20px 20px;
}

.success-icon .icon {
  font-size: 48px;
  color: #67c23a;
  margin-bottom: 16px;
  display: block;
}

.success-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.success-subtitle {
  color: #666;
  font-size: 14px;
}

.order-info {
  padding: 0 24px 20px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  color: #666;
  font-size: 14px;
}

.info-item .value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.info-item .value.price {
  color: #f56c6c;
  font-weight: 600;
}

.success-actions {
  padding: 20px 24px 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  flex: 1;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  text-align: center;
}

.secondary-btn {
  background-color: #f5f5f5;
  color: #666;
}

.secondary-btn:hover {
  background-color: #e8e8e8;
}

.primary-btn {
  background-color: #409eff;
  color: white;
}

.primary-btn:hover {
  background-color: #337ecc;
}

/* 错误提示样式 */
.error-toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #f56c6c;
  color: white;
  padding: 12px 20px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
  z-index: 2000;
  font-size: 14px;
  max-width: 400px;
  text-align: center;
}
</style>
